package bma.common.langutil.ai.stack;

import bma.common.langutil.ai.vm.AIContext;
import bma.common.langutil.core.Preconditions;

/**
 * 
 * @author guanzhong
 * @since 1.0 (imported from BMA.ESP Project)
 * 
 * @param <RESP_TYPE>
 */
public class AIStackReentrant<RESP_TYPE> implements AIStack<RESP_TYPE> {

	protected Runnable task(final RESP_TYPE result, final Throwable t) {
		return new Runnable() {
			@Override
			public void run() {
				try {
					if (t != null) {
						delegate.failure(t);
					} else {
						delegate.success(result);
					}
				} catch (Exception e) {
				}
			}
		};
	}

	protected final AIStack<RESP_TYPE> delegate;
	protected final AIContext context;

	public AIStackReentrant(AIStack<RESP_TYPE> delegate, AIContext ctx) {
		super();
		Preconditions.checkNotNull(ctx);
		this.delegate = delegate;
		this.context = ctx;
	}

	@Override
	public AIStack<?> getParent() {
		return delegate;
	}

	@Override
	public boolean success(RESP_TYPE result) {
		context.execute(task(result, null));
		return false;
	}

	@Override
	public boolean failure(Throwable t) {
		context.execute(task(null, t));
		return false;
	}

}
